package com.sxpi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxpi.common.result.Result;
import com.sxpi.convert.UsersConvert;
import com.sxpi.mapper.*;
import com.sxpi.model.entity.*;
import com.sxpi.model.page.PageResult;
import com.sxpi.model.vo.UsersVo;
import com.sxpi.service.UsersService;
import com.sxpi.utils.JwtUtil;
import com.sxpi.utils.MinioUtils;
import com.sxpi.utils.WxUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@Service
@Slf4j
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    @Resource
    private UsersMapper usersMapper;
    @Resource
    private CostumesMapper costumesMapper;
    @Resource
    private WorksMapper worksMapper;
    @Resource
    private WorksImageMapper worksImageMapper;
    @Resource
    private BookingsMapper bookingsMapper;
    @Resource
    private CouponsItemMapper couponsItemMapper;
    @Resource
    private CouponsMapper couponsMapper;
    @Resource
    private CostumeImagesMapper costumeImagesMapper;
    @Resource
    private LikesMapper likesMapper;
    @Value("${wx.appId}")
    private String appId;

    @Value("${wx.appSecret}")
    private String appSecret;
    @Autowired
    private MinioUtils minioUtils;

    @Override
    public Result<UsersVo> login(Map<String, String> loginParams) {
        String wxCode = (String) loginParams.get("wxCode");
        String openIdCode = (String) loginParams.get("openIdCode");
        String accessToken = WxUtil.getAccessToken(appId, appSecret);
        // 2. 获取手机号信息
        String phone = WxUtil.getPhoneNumber(accessToken, wxCode);

        LambdaQueryWrapper<Users> eq = new LambdaQueryWrapper<Users>().eq(Users::getPhone, phone);
        Users users = usersMapper.selectOne(eq);
        if(!Objects.isNull(users)){
            UsersVo usersVo = UsersConvert.INSTANCE.convertVoToEntity(users);
            String jwt = JwtUtil.createJWT(usersVo.getPhone());
            usersVo.setToken(jwt);
            return Result.build(usersVo,200, "登录成功");
        }
        Users users1 = new Users();

        users1.setPhone(phone);
        users1.setNickname("用户"+phone.substring(7,11));
        usersMapper.insert(users1);
        UsersVo usersVo = UsersConvert.INSTANCE.convertVoToEntity(users1);
        usersVo.setToken(JwtUtil.createJWT(usersVo.getPhone()));

        return Result.build(usersVo,200, "注册成功");

    }

    @Override
    public Result<PageResult<UsersVo>> getAllUsers(Integer pageNo, Integer pageSize, String nickName, String phone, String gender) {
        Page<Users> usersPage = new Page<>(pageNo,pageSize);

        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!Objects.isNull(nickName),Users::getNickname,nickName);
        wrapper.eq(!Objects.isNull(phone),Users::getPhone,phone);
        wrapper.eq(!Objects.isNull(gender),Users::getGender,gender);

        Page<Users> usersPage1 = usersMapper.selectPage(usersPage, wrapper);

        List<Users> records = usersPage1.getRecords();

        List<UsersVo> usersVos = UsersConvert.INSTANCE.convertVoToEntity(records);

        PageResult<UsersVo> usersVoPageResult = new PageResult<>();
        usersVoPageResult.setPageNo(pageNo);
        usersVoPageResult.setPageSize(pageSize);
        usersVoPageResult.setResult(usersVos);
        usersVoPageResult.setTotal((int) usersPage1.getTotal());

        return Result.ok(usersVoPageResult);
    }

    @Override
    public Result<UsersVo> updateUserInformation(Long userId, Users userInfo) {
        // 1. 查询用户是否存在
        Users existingUser = usersMapper.selectById(userId);
        if (existingUser == null) {
            return Result.build(null,400,"用户不存在");
        }

        // 2. 更新用户信息
        if (userInfo.getBirthday() != null) {
            existingUser.setBirthday(userInfo.getBirthday());
        }
        if (userInfo.getUsername() != null) {
            existingUser.setUsername(userInfo.getUsername());
        }
        if (userInfo.getGender() != null) {
            existingUser.setGender(userInfo.getGender());
        }
        if (userInfo.getEmail() != null) {
            existingUser.setEmail(userInfo.getEmail());
        }
        if (userInfo.getPhone() != null) {
            existingUser.setPhone(userInfo.getPhone());
        }
        if (userInfo.getNickname() != null) {
            existingUser.setNickname(userInfo.getNickname());
        }
        if(userInfo.getAvatarUrl() != null){
            existingUser.setAvatarUrl(userInfo.getAvatarUrl());
        }
        // 3. 执行更新操作
        int updated = usersMapper.updateById(existingUser);
        if (updated > 0) {
            // 4. 转换为 VO 对象并返回
            UsersVo usersVo = new UsersVo();
            // 设置更新后的用户信息
            usersVo.setId(existingUser.getId());
            usersVo.setBirthday(existingUser.getBirthday());
            usersVo.setGender(existingUser.getGender());
            usersVo.setEmail(existingUser.getEmail());
            usersVo.setPhone(existingUser.getPhone());
            usersVo.setNickname(existingUser.getNickname());
            usersVo.setAvatarUrl(existingUser.getAvatarUrl());

            return Result.ok(usersVo);
        }

        return Result.build(null,400,"更新失败");
    }
    @Transactional
    @Override
    public Result<String> updateAvatar(Long userId, MultipartFile file) {;

         String fileName = file.getOriginalFilename();
        String substring = null;
        if (fileName != null) {
            substring = fileName.substring(fileName.lastIndexOf("."));
        }
        String objName = UUID.randomUUID().toString()+substring;

        LambdaUpdateWrapper<Users> set = new LambdaUpdateWrapper<Users>().eq(Users::getId, userId).set(Users::getAvatarUrl, objName);
        int update = usersMapper.update(new Users(), set);
        minioUtils.upload(file,objName);

        return Result.ok(objName);
    }

    @Override
    public Result<UsersVo> loginPhone(Long phone) {
        return null;
    }

    @Override
    public Result<Map> getUserDetailWithCoupons(Long userId) {
        // 查询用户基本信息
        Users user = usersMapper.selectById(userId);
        if (user == null) {
            return Result.build(null, 400,"用户不存在");
        }

        // 查询用户优惠券数量
        Integer validCouponCount = 0; // 用于统计状态为1的优惠券数量
        List<CouponsItem> coupons = couponsItemMapper.selectList(new LambdaQueryWrapper<CouponsItem>()
                .eq(CouponsItem::getUserId, userId));

        for (CouponsItem coupon : coupons) {
            List<Coupons> coupons1 = couponsMapper.selectList(
                    new LambdaQueryWrapper<Coupons>()
                            .eq(Coupons::getId, coupon.getCouponsId())
                            .eq(Coupons::getStatus, 1)
            );
            validCouponCount += coupons1.size();
        }

//        查询用户订单status为1的数量
        Integer orderCount = Math.toIntExact(bookingsMapper.selectCount(new LambdaQueryWrapper<Bookings>().eq(Bookings::getUserId, userId).eq(Bookings::getStatus, 3)));

        // 构建已拍列���数据
        List<Map<String, Object>> yiPaiList = new ArrayList<>();
        // 查询用户已支付的订单
        List<Bookings> bookings = bookingsMapper.selectList(
                new LambdaQueryWrapper<Bookings>()
                        .eq(Bookings::getUserId, userId)
                        .eq(Bookings::getPay, 1));

        // 遍历订单，获取对应的服装信息
        for (Bookings booking : bookings) {
            // 根据订单中的服装ID查询服装信息
            Costumes costume = costumesMapper.selectById(booking.getCostumeId());
            if (costume != null) {
                // 查询服装的主图
                CostumeImages mainImage = costumeImagesMapper.selectOne(
                        new LambdaQueryWrapper<CostumeImages>()
                                .eq(CostumeImages::getCostumeId, costume.getId())
                                .eq(CostumeImages::getIsMain, 1));

                Map<String, Object> yiPaiMap = new HashMap<>();
                yiPaiMap.put("costumesId", costume.getId());
                yiPaiMap.put("costumesImage", mainImage != null ? mainImage.getUrl() : null);
                yiPaiMap.put("name", costume.getName());

                yiPaiList.add(yiPaiMap);
            }
        }

        // 查询用户想拍作品
        List<Works> works = worksMapper.selectList(new LambdaQueryWrapper<Works>()
                .eq(Works::getUserId, userId));
        // 构建想拍列表数据
        List<Map<String, Object>> likePaiList = new ArrayList<>();

        // 构建想拍列表数据
        Map<String, Object> workMap = new HashMap<>();

        for (Works work : works) {
            Map<String, Object> workMap1 = new HashMap<>();
            // 获取作品的第一张图片
            WorkImages firstImage = worksImageMapper.selectOne(new LambdaQueryWrapper<WorkImages>()
                    .eq(WorkImages::getWorkId, work.getId())
                    .orderByAsc(WorkImages::getId)
                    .last("LIMIT 1"));

            // 统计该作品的点赞数量
            Long likeCount = likesMapper.selectCount(new LambdaQueryWrapper<Likes>()
                    .eq(Likes::getWorkId, work.getId()));
            Users users = usersMapper.selectOne(new LambdaQueryWrapper<Users>().eq(Users::getId, work.getUserId()));

            workMap1.put("workId", work.getId());
            workMap1.put("workImage", firstImage != null ? firstImage.getImageUrl() : null);
            workMap1.put("title", work.getTitle());
            workMap1.put("likeCount", likeCount);  // 添加点赞数量
            workMap1.put("nickname", users.getNickname());

            likePaiList.add(workMap1);
        }

        workMap.put("work", likePaiList);

        // 构建服装列表数据
        List<Likes> likes = likesMapper.selectList(new LambdaQueryWrapper<Likes>()
                .eq(Likes::getUserId, userId));
        List<Map<String, Object>> costumesList = new ArrayList<>();

        likes.forEach(item -> {
            List<Costumes> costumes = costumesMapper.selectList(new LambdaQueryWrapper<Costumes>().eq(Costumes::getId, item.getCostumesId()));
            for (Costumes costume : costumes) {
                Map<String, Object> costumeMap = new HashMap<>();
                LambdaQueryWrapper<CostumeImages> eq = new LambdaQueryWrapper<CostumeImages>()
                        .eq(CostumeImages::getCostumeId, costume.getId()).eq(CostumeImages::getIsMain, 1);
                CostumeImages costumeImages = costumeImagesMapper.selectOne(eq);
                costumeMap.put("costumesImage", costumeImages.getUrl());
                costumeMap.put("costumesId", costume.getId());
                costumeMap.put("name", costume.getName());  // 假设Costumes实体有name字段
                costumesList.add(costumeMap);
            }
        });




        workMap.put("costumes", costumesList);

        // 组装返回数据
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("userInfo", user);
        resultMap.put("couponCount", validCouponCount);
        resultMap.put("orderCount", orderCount);
        resultMap.put("yiPai", yiPaiList);  // 添加已拍列表数据
        resultMap.put("likePai", workMap);  // 添加想拍列表数据

        return Result.ok(resultMap);
    }

}